#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import memcache

class Status(webapp.RequestHandler):
	
	def get(self, product_id):
		feed = memcache.get('feed');
		
		if feed is None:
			import gdata.spreadsheet.service
			import gdata.service
			import gdata.urlfetch
			gdata.service.http_request_handler = gdata.urlfetch
			client = gdata.spreadsheet.service.SpreadsheetsService()
			key = 'pfIfF3LLjIO0Ls5MOCRrlDw'
			wksht_id = 2
			feed = client.GetListFeed(key, wksht_id, visibility='public', projection='values')
			memcache.set('feed', feed, time=5)
		
		if int(product_id)-1 > len(feed.entry):
			# red light if out of range
			img = open('red.png', 'r').read()
			self.response.headers['Content-Type'] = 'image/png'
			self.response.headers['Cache-Control'] = 'no-cache'
			self.response.out.write(img)
		else:
			if feed.entry[int(product_id)-1].title.text == "2":
				img = open('green.png', 'r').read()
				self.response.headers['Content-Type'] = 'image/png'
				self.response.headers['Cache-Control'] = 'no-cache'
				self.response.out.write(img)
				
			elif feed.entry[int(product_id)-1].title.text == "1":
				img = open('yellow.png', 'r').read()
				self.response.headers['Content-Type'] = 'image/png'
				self.response.headers['Cache-Control'] = 'no-cache'
				self.response.out.write(img)
				
			# red status otherwise
			else:
				img = open('red.png', 'r').read()
				self.response.headers['Content-Type'] = 'image/png'
				self.response.headers['Cache-Control'] = 'no-cache'
				self.response.out.write(img)


def main():
	application = webapp.WSGIApplication([('/status/([0-9]+)', Status)], debug=True)
	wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
	main()